package com.gxc.mongo.service;

import com.gxc.mongo.dao.SpitRepository;
import com.gxc.mongo.entity.Spit;
import com.mongodb.client.result.UpdateResult;
import java.util.List;
import java.util.UUID;
import javax.annotation.Resource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.CriteriaDefinition;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

/**
 * SpitService.
 *
 * @author 宫新程
 * @since 2019/1/16 4:52 PM
 */
@Service
public class SpitService {

  @Resource private SpitRepository spitRepository;
  @Resource private MongoTemplate mongoTemplate;

  /** 查询全部. */
  public List<Spit> findAll() {
    return spitRepository.findAll();
  }

  /** 分页查询. */
  public Page<Spit> findAll(Integer pageNum, Integer pageSize) {
    Pageable pageable = PageRequest.of(pageNum - 1, pageSize);
    return spitRepository.findAll(pageable);
  }

  /** 根据id查询. */
  public Spit findById(String id) {
    return spitRepository.findById(id).get();
  }

  /** 保存. */
  public void save(Spit spit) {
    // 设置_id
    spit.set_id(UUID.randomUUID().toString().replace("-", ""));
    this.spitRepository.save(spit);
  }

  /** 更新. */
  public void update(Spit spit) {
    this.spitRepository.save(spit);
  }

  /** 删除. */
  public void deleteById(String id) {
    this.spitRepository.deleteById(id);
  }

  /** 访问量大于1000的. */
  public List<Spit> findVisitsGl1000() {
    return this.spitRepository.findByVisitsIsGreaterThan(1000);
  }

  /** 点赞数加一. */  // db.spit.update({"_id":"1"}, {$inc:NumberInt(1)})
  public void thumbup(String spitId) {
    Query query = new Query();
    query.addCriteria(Criteria.where("_id").is(spitId));
    Update update = new Update();
    update.inc("thumbup", 1);
    mongoTemplate.updateFirst(query, update, "spit");
  }
}
